# -*- coding: utf-8 -*-
import bs4,requests,re,json,lxml
# 控制台输出移除SSL认证警告
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

jira_url = 'https://jira.mingyuanyun.com/login.jsp'
headers = {
    'Host': 'jira.mingyuanyun.com',
    'Connection': 'keep-alive',
    'Accept': '*/*',
    'X-Requested-With': 'XMLHttpRequest',
    'X-PJAX': 'true',
    'X-AUSERNAME': 'wup06',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
}

LoginHeaders = {
    'Host': 'jira.mingyuanyun.com',
    'Connection': 'keep-alive',
    'Content-Length': '121',
    'Cache-Control': 'max-age=0',
    'Origin': 'https://jira.mingyuanyun.com',
    'Upgrade-Insecure-Requests': '1',
    'Content-Type': 'application/x-www-form-urlencoded',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
    'Sec-Fetch-User': '?1',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    'Sec-Fetch-Site': 'same-origin',
    'Sec-Fetch-Mode': 'navigate',
    'Referer': 'https://jira.mingyuanyun.com/login.jsp',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
}
#设置代理，用户fiddler抓取
proxies = {
        "http": "127.0.0.1:8888"
    }
#初始化session，后续请求就能自动带上cookies
sess = requests.session()

def tags_val(tag, key='', index=0):
    '''
    return html tag list attribute @key @index
    if @key is empty, return tag content
    '''
    if len(tag) == 0 or len(tag) <= index:
        return ''
    elif key:
        txt = tag[index].get(key)
        return txt.strip(' \t\r\n') if txt else ''
    else:
        txt = tag[index].text
        return txt.strip(' \t\r\n') if txt else ''


def tag_val(tag, key=''):
    '''
    return html tag attribute @key
    if @key is empty, return tag content
    '''
    if tag is None:
        return ''
    elif key:
        txt = tag.get(key)
        return txt.strip(' \t\r\n') if txt else ''
    else:
        txt = tag.text
        return txt.strip(' \t\r\n') if txt else ''

#登录
def login():
    # data= 'userId=wf'+user+'&userPassword='+passwd
    data = {
        'os_username':'wup06',
        'os_password':'xxxxxxx',
        'os_cookie':'true',
        'os_destination': '',
        'user_role': '',
        'atl_token': '',
        'login': '登录'
    }
    resp = sess.post(
        url=jira_url,
        headers=LoginHeaders, data=data,proxies=proxies, verify=False)
    if resp.status_code ==200:
        pass
    else:
        print ('登录失败')

def get_sprint_id(sprint_name):
    url = "https://jira.mingyuanyun.com/rest/greenhopper/1.0/xboard/work/allData.json?rapidViewId=50&selectedProjectKey=GZL&_=1606285584271"
    resp = sess.get(url,proxies=proxies, verify=False)
    resp_dict = json.loads(resp.text)
    sprints = resp_dict["sprintsData"]["sprints"]
    for sprint in sprints:
        if sprint_name in sprint["name"]:
            # print(sprint["id"])
            return sprint["id"]

#请求jira信息，获取文本
def GetText(keyword,title):
    url = "https://jira.mingyuanyun.com/rest/greenhopper/1.0/xboard/work/allData.json?rapidViewId=50&selectedProjectKey=GZL&activeSprints="+str(keyword)+"&_=1606207012848"
    resp = sess.get(url,proxies=proxies,headers=headers, verify=False)
    resp_dict = json.loads(resp.text)
    issues_list = resp_dict["issuesData"]["issues"]
    # print(issues)

    result = {}
    for jira in issues_list:
        # map(lambda x: x in v,title) 得到[True,False]这种数组 且 经办人不是冯会芳、刘俐俊、吴鹏、王健


        try:
            if True in map(lambda x: x in jira["summary"], title) and jira["assignee"] not in ['fenghf', 'liulj',
                                                                                               'wup06', 'wangj38']:
                # if "2.0.27.15" in jira["summary"]:
                result[jira["key"]] = jira["summary"] + " --" + jira["assigneeName"]
                # print(jira["key"]+jira["summary"]+" --"+jira["assigneeName"])
        except:
            print(f"{jira['typeName']} {jira['summary']}不统计")

    # print result
    # 返回字典，key是jira编号，value是jira标题+经办人
    return result

def jira_action(sprint_name,version):
    login()
    id = get_sprint_id(sprint_name)
    return GetText(id, version)

# if __name__ == '__main__':
#     sprint_name = u"工作流：11sp1（1109-1127）"
#     version = ["2.0.27.15", "27.15"]
#     login()
#     id = get_sprint_id(sprint_name)